﻿using LPBToolsLib;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;

namespace AUSer_V1
{
    public class AUSLogin
    {
        static private Exception tLastError { get; set; } = null;

        static bool hasError { get { return tLastError != null; } }

        public static Exception LastError
        {
            get
            {
                Exception eTmp = tLastError;
                tLastError = null;
                return eTmp;
            }
            set { tLastError = value; }
        }
        public static StationsOnline tStationOnlineSer { get; }=new StationsOnline();

        public static MySQLConfigWebCFG tDBConfig { get; }=new MySQLConfigWebCFG(WebConfigurationManager.AppSettings);

        /// <summary>
        /// 工作站登录操作
        /// https://localhost:44303/AUSMain.aspx?api=login&username=admin&userpass=e10adc3949ba59abbe56e057f20f883e&modelname=test
        /// </summary>
        /// <param name="sUserName">username</param>
        /// <param name="sUserPass">userpass</param>
        /// <param name="sModelName">modelname</param>
        /// <returns></returns>
        public static Dictionary<string, object> StationLogin(Dictionary<string, object> tPostDatas, out int iErrCode, out string errMsg)
        {
            errMsg = "";
            iErrCode = -1; 
            Dictionary<string, object> tResult = null;
            try
            {
                if ((tPostDatas != null)
                    && tPostDatas.ContainsKey("username")
                    && (!string.IsNullOrEmpty(tPostDatas["username"].ToString()))
                    && tPostDatas.ContainsKey("userpass")
                    && (!string.IsNullOrEmpty(tPostDatas["userpass"].ToString()))
                    && tPostDatas.ContainsKey("modelname")
                    && (!string.IsNullOrEmpty(tPostDatas["modelname"].ToString())))
                {
                    string sUserName = MySQLHelper.clearSQLValue(tPostDatas["username"].ToString());
                    string sUserPass = MySQLHelper.clearSQLValue(tPostDatas["userpass"].ToString());
                    string sModelName = MySQLHelper.clearSQLValue(tPostDatas["modelname"].ToString());

                    if ((!string.IsNullOrEmpty(sUserName)) && (!string.IsNullOrEmpty(sUserPass))
                        && (!string.IsNullOrEmpty(sModelName)))
                    {
                        MySQLHelper tSQLHelper = new MySQLHelper(tDBConfig);
                        string sSQL = "SELECT UserInfo FROM appusers WHERE LoginName='{0}' and MD5(LoginPass)='{1}' and ModelName='{2}' and UserLevel>0";
                        sSQL = string.Format(sSQL, sUserName, sUserPass, sModelName);
                        object tR = tSQLHelper.runSelect(sSQL);
                        string sUserInfo = (tR != null) ? tR.ToString() : "";
                        if (!string.IsNullOrEmpty(sUserInfo))
                        {
                            Dictionary<string, object> tUserInfo = null;
                            try
                            {                                
                                tUserInfo = JsonConvert.DeserializeObject<Dictionary<string, object>>(sUserInfo);
                            }
                            catch (Exception ex)
                            {
                                errMsg = "不可识别用户身份信息！";
                                iErrCode = -3;
                            }
                            if ((tUserInfo != null) && (tUserInfo.Count > 0))
                            {
                                StationInfo tStation = new StationInfo(0,tUserInfo);
                                tStation =tStationOnlineSer.createNewStation(tStation);
                                if (tStation != null)
                                {
                                    tResult = new Dictionary<string, object>();
                                    //tResult.Add("info", tUserInfo);
                                    tResult.Add("token", tStation.Token);
                                    tResult.Add("timeout", tStation.LastSecond);
                                    errMsg = "ok";
                                    iErrCode = 0;
                                    return tResult;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                LastError = ex;
                return null;
            }
            return null;
        }

        /// <summary>
        /// 工作模组获得Token对应的工作站信息
        /// 输入参数：statoken
        /// </summary>
        /// <param name="tPostDatas"></param>
        /// <param name="iErrCode"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetStationInfo(Dictionary<string, object> tPostDatas, out int iErrCode, out string errMsg)
        {
            errMsg = "";
            iErrCode = -1;
            try
            {
                if ((tPostDatas != null)
                    && tPostDatas.ContainsKey("statoken")
                    && (!string.IsNullOrEmpty(tPostDatas["statoken"].ToString())))
                {
                    string sStaToken = MySQLHelper.clearSQLValue(tPostDatas["statoken"].ToString());                   
                    if (!string.IsNullOrEmpty(sStaToken))
                    {
                        StationInfo tStation = tStationOnlineSer.getStation(sStaToken);
                        if (tStation != null)
                        {
                            try
                            {
                                Dictionary<string, object> tResult = (Dictionary<string, object>)tStation.Datas;
                                if (tResult != null)
                                {
                                    tResult.Add("token", tStation.Token);
                                    tResult.Add("timeout", tStation.LastSecond);
                                    errMsg = "ok";
                                    iErrCode = 0;
                                    return tResult;
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                LastError = ex;
                return null;
            }
            return null;
        }

        /// <summary>
        /// 工作站标记在线
        /// 输入参数：statoken
        /// </summary>
        /// <param name="tPostDatas"></param>
        /// <param name="iErrCode"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static Dictionary<string, object> StationLoop(Dictionary<string, object> tPostDatas, out int iErrCode, out string errMsg)
        {
            errMsg = "";
            iErrCode = -1;
            Dictionary<string, object> tResult = null;
            try
            {
                if ((tPostDatas != null)
                    && tPostDatas.ContainsKey("statoken")
                    && (!string.IsNullOrEmpty(tPostDatas["statoken"].ToString())))
                {
                    string sStaToken = MySQLHelper.clearSQLValue(tPostDatas["statoken"].ToString());
                    if (!string.IsNullOrEmpty(sStaToken))
                    {
                        StationInfo tStation = tStationOnlineSer.reflashStation(sStaToken);
                        if (tStation != null)
                        {
                            tResult = (Dictionary<string, object>)tStation.Datas;
                            tResult.Add("token", tStation.Token);
                            errMsg = "ok";
                            iErrCode = 0;
                            return tResult;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                LastError = ex;
                return null;
            }
            return null;
        }
    }
}